#include "head.h"
int sendfd(int pipefd, int fdtosend){
    struct msghdr msghdr;
    bzero(&msghdr,sizeof(msghdr));// name 设置为NULL和0 这一步绝对不能省略
    // 消息正文部分
    char buf[] = "hello";
    struct iovec iov[1];//离散的区域长度为1，则退化成连续的
    iov[0].iov_base = buf;//0号元素首地址是buf
    iov[0].iov_len = 5;//0号元素的长度是5个字节
    msghdr.msg_iov = iov;
    msghdr.msg_iovlen = 1;
    // 消息的控制部分
    struct cmsghdr * pcmsg = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int)));//变长结构体，只能申请在堆上
    pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level = SOL_SOCKET;
    pcmsg->cmsg_type = SCM_RIGHTS;// 传递的类型是文件对象 
    *(int *)CMSG_DATA(pcmsg) = fdtosend;// 取出data的地址，强转成int *，解引用并赋值
    msghdr.msg_control = pcmsg;
    msghdr.msg_controllen = CMSG_LEN(sizeof(int));
    sendmsg(pipefd,&msghdr,0);
    return 0;
}
int recvfd(int pipefd, int *pfdtorecv){
    struct msghdr msghdr;
    bzero(&msghdr,sizeof(msghdr));// name 设置为NULL和0 这一步绝对不能省略
    // 消息正文部分
    char buf[6] = {0} ;
    struct iovec iov[1];//离散的区域长度为1，则退化成连续的
    iov[0].iov_base = buf;//0号元素首地址是buf
    iov[0].iov_len = 5;//0号元素的长度是5个字节
    msghdr.msg_iov = iov;
    msghdr.msg_iovlen = 1;
    // 消息的控制部分
    struct cmsghdr * pcmsg = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int)));//变长结构体，只能申请在堆上
    pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level = SOL_SOCKET;
    pcmsg->cmsg_type = SCM_RIGHTS;// 传递的类型是文件对象 
    msghdr.msg_control = pcmsg;
    msghdr.msg_controllen = CMSG_LEN(sizeof(int));
    recvmsg(pipefd,&msghdr,0);
    //printf("buf = %s\n", buf);
    //printf("recvfd = %d\n",*(int *)CMSG_DATA(pcmsg));
    *pfdtorecv = *(int *)CMSG_DATA(pcmsg);
    return 0;
}
